<template>
    <div class='post'>
        <div class="container">
            <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" class="search-con">
                <el-form-item label="岗位名称" prop="key">
                    <el-input v-model="queryParams.key" placeholder="请输入" clearable size="small" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
            <el-row :gutter="10" class="mb8">
                <el-col :span="22">
                    <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleBtn('add')" v-hasPermi="['user:post:add']">
                        新增</el-button>
                </el-col>
                <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
            <el-table border v-loading="loading" :data="tableList" ref="tableList" v-tableHeight :height="tableList&&tableList.length>0?'900px':'120px'">
                <el-table-column label="序号" align="center" prop="id" />
                <el-table-column label="岗位名称" align="center" prop="name" />
                <!-- <el-table-column label="关联账号数" align="center" prop="name" />
                <el-table-column label="关联账号数" align="center" prop="name" />
                <el-table-column label="创建日期" align="center" prop="name" />
                <el-table-column label="状态" align="center" prop="status">
                    <template slot-scope="scope">
                        <span>
                            {{selectDictLabel(statusList, scope.row.status)}}
                        </span>
                    </template>
                </el-table-column> -->
                <el-table-column label="状态" align="center" prop="status">
                    <template slot-scope="scope">
                        <span>
                            {{selectDictLabel(statusList, scope.row.status)}}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <!-- <el-button size="mini" type="text" icon="el-icon-s-order" @click="setPermissions(scope.row)" v-hasPermi="['user:post:permission']">
                            菜单权限
                        </el-button> -->
                        <el-button size="mini" type="text" icon="el-icon-edit" @click="handleBtn('edit',scope.row);" v-hasPermi="['user:post:edit']">
                            编辑
                        </el-button>
                        <el-button v-if="scope.row.status==0" size="mini" type="text" @click="handleAble(scope.row)" v-hasPermi="['user:post:stop']">停用
                        </el-button>
                        <el-button v-if="scope.row.status==1" size="mini" type="text" @click="handleAble(scope.row)" v-hasPermi="['user:post:start']">启用
                        </el-button>
                        <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['user:post:del']">
                            删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="pageCount>0" :pageCount="pageCount" :page.sync="queryParams.page" :limit.sync="queryParams.limit" @pagination="getList" />
        </div>
        <el-dialog :title="handleShow=='add'?'新增':'编辑'" visible v-if="handleShow" @close="close()" width="600px" append-to-body :close-on-click-modal="false">
            <el-form ref="form" :model="form" :rules="rules" label-width="80px" v-loading="formLoading">
                <el-row>
                    <el-col :span="24" v-if="handleShow=='menu'">
                        <el-form-item label="菜单权限">
                            <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event)">展开/折叠</el-checkbox>
                            <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选</el-checkbox>
                            <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event)">父子联动</el-checkbox>
                            <el-tree class="tree-border" :data="menuOptions" show-checkbox ref="menu" node-key="id" :default-checked-keys="defaultKeys"
                                :check-strictly="!form.menuCheckStrictly" empty-text="加载中，请稍后" :props="defaultProps"></el-tree>
                        </el-form-item>
                    </el-col>
                    <template v-else>
                        <el-col :span="12">
                            <el-form-item label="部门" prop="sector_id">
                                <el-select v-model="form.sector_id" placeholder="请输入选择" clearable size="small" filterable>
                                    <el-option v-for="dict in depList" :key="dict.id" :label="dict.name" :value="dict.id" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="岗位名称" prop="name">
                                <el-input v-model="form.name" placeholder="请输入岗位名称" />
                            </el-form-item>
                        </el-col>
                    </template>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="close()">取 消</el-button>
                <el-button type="primary" @click="submit" :disabled="formLoading">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import { getJobsLists, getSectorListsAll, setJobs, setJobsStatus, delJobs } from "@/api/user/post.js"
import { setAuth, getAuth, getAuthMenusLists } from "@/api/common.js"
import { departStatus } from "@/api/dictionary"
import {
    saveObjArr,
    getObjArr
} from "@/utils/ruoyi.js"
import throttle from 'lodash.throttle'
export default {
    name: 'post',
    props: {

    },
    data() {
        return {
            showSearch: true,
            loading: false,
            pageCount: 0,
            total: 0,
            queryParams: {
                page: 1,
                limit: 20,
                key: null,
                is_show_hide: 1
            },
            tableList: [],
            statusList: departStatus,
            handleShow: "",
            formLoading: false,
            form: {
                sector_id: null,
                id: null,
                name: null,
            },
            rules: {
                sector_id: [{ required: true, message: "请选择部门", trigger: "change" }],
                name: [{ required: true, message: '请输入岗位名称', trigger: 'blur' }],
            },
            depList: [],
            menuExpand: false,
            menuNodeAll: false,
            // 菜单列表
            menuOptions: [],
            defaultProps: {
                children: "sub",
                label: "title"
            },
            defaultKeys: []
        }
    },
    created() {
        let fun = [
            // getAuthMenusLists({ menu_types: "0,1,2" }),
        ]
        Promise.all(fun).then(res => {
            // this.menuOptions = res[0].data
            console.log(this.menuOptions, "this.menuOptions")
            this.getList()
        })
    },
    methods: {
        getList() {
            this.loading = true;
            getJobsLists(this.queryParams).then(res => {
                // this.tableList = res.data.lists;
                this.tableList = res.data;
                // this.pageCount = res.data.pageCount;
                this.loading = false;
            });
        },
        handleQuery() {
            this.queryParams.page = 1;
            this.getList();
        },
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        close() {
            this.menuExpand = false
            this.menuNodeAll = false
            this.form = {}
            this.handleShow = ""
        },
        handleBtn(type, row) {
            getSectorListsAll().then(res => {
                this.depList = res.data
            })
            if (row) {
                this.form = JSON.parse(JSON.stringify(row));
            }
            this.handleShow = type
        },
        handleAble(row) {
            let label = row.status == 0 ? '停用' : '启用';
            this.$confirm(`是否将“${row.name}”${label}?`, "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return setJobsStatus({ jobs_id: row.id });
            }).then(() => {
                this.getList();
                this.msgSuccess(`${label}成功`);
            })
        },
        handleDelete(row) {
            this.$confirm('是否确认删除' + '"' + row.name + '"' + '?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return delJobs({ jobs_id: row.id });
            }).then(() => {
                this.getList();
                this.msgSuccess("删除成功");
            })
        },
        // 树权限（展开/折叠）
        handleCheckedTreeExpand(value) {
            let treeList = this.menuOptions;
            for (let i = 0; i < treeList.length; i++) {
                this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
            }
        },
        // 树权限（全选/全不选）
        handleCheckedTreeNodeAll(value) {
            this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
        },
        // 树权限（父子联动）
        handleCheckedTreeConnect(value) {
            this.form.menuCheckStrictly = value ? true : false;
        },
        // 所有菜单节点数据
        getMenuAllCheckedKeys() {
            // 目前被选中的菜单节点
            let checkedKeys = this.$refs.menu.getCheckedKeys();
            // 半选中的菜单节点
            let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
            checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
            return checkedKeys;
        },
        setPermissions(row) {
            getAuth({ job_id: row.id }).then(res => {
                this.$nextTick(() => {
                    this.defaultKeys = res.data.split(",")
                })
                this.form.job_id = row.id
                this.title = '菜单权限';
                this.handleShow = 'menu'
            })
        },

        submit: throttle(function () {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.formLoading = true;
                    let fun;
                    if (this.handleShow == 'menu') {
                        let menuIds = this.getMenuAllCheckedKeys()
                        this.form.menu_ids = menuIds.join(",")
                        delete this.form.id
                        delete this.form.name
                        fun = setAuth
                    } else {
                        fun = setJobs
                        this.form.jobs_id = this.form.id ? this.form.id : null
                    }
                    fun(this.form).then(res => {
                        this.msgSuccess("操作成功！");
                        this.close()
                        this.formLoading = false;
                        this.getList();
                    }).catch(() => {
                        this.formLoading = false;
                    })
                }
            })
        }, 1000, { trailing: false }),
    }
}
</script>

<style lang='scss' scoped>
</style>
